<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>本地代码上传助手</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .drag-area {
            border: 2px dashed #cbd5e0;
            transition: all 0.3s ease;
        }
        .drag-area.dragover {
            border-color: #4299e1;
            background-color: #ebf8ff;
        }
        .file-tree {
            font-family: 'Consolas', 'Monaco', monospace;
        }
        .code-editor {
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 14px;
            line-height: 1.5;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-50">
    <div class="container mx-auto px-4 py-8">
        <div class="max-w-6xl mx-auto">
            <!-- 标题 -->
            <div class="text-center mb-8">
                <h1 class="text-4xl font-bold text-gray-800 mb-2">
                    <i class="fas fa-cloud-upload-alt text-blue-500"></i>
                    本地代码上传助手
                </h1>
                <p class="text-gray-600">拖拽上传ZIP/TAR压缩包，自动解压并运行你的代码</p>
            </div>

            <!-- 上传区域 -->
            <div class="bg-white rounded-lg shadow-lg p-6 mb-6">
                <div id="uploadArea" class="drag-area rounded-lg p-8 text-center cursor-pointer">
                    <i class="fas fa-upload text-4xl text-gray-400 mb-4"></i>
                    <h3 class="text-xl font-semibold text-gray-700 mb-2">拖拽文件到此处</h3>
                    <p class="text-gray-500 mb-4">或点击选择文件</p>
                    <input type="file" id="fileInput" accept=".zip,.tar,.gz,.tgz" class="hidden">
                    <button onclick="document.getElementById('fileInput').click()" 
                            class="bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition">
                        选择文件
                    </button>
                </div>
                <div id="uploadStatus" class="mt-4 text-center hidden">
                    <div class="loading"></div>
                    <span class="ml-2">正在上传并解压...</span>
                </div>
            </div>

            <!-- 项目展示区域 -->
            <div id="projectArea" class="hidden">
                <div class="bg-white rounded-lg shadow-lg p-6">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">
                        <i class="fas fa-folder-open text-green-500"></i>
                        <span id="projectName"></span>
                    </h2>
                    
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- 文件树 -->
                        <div class="lg:col-span-1">
                            <h3 class="text-lg font-semibold text-gray-700 mb-3">文件结构</h3>
                            <div id="fileTree" class="file-tree bg-gray-50 rounded p-4 overflow-auto max-h-96">
                                <!-- 文件树将在这里动态生成 -->
                            </div>
                        </div>
                        
                        <!-- 代码编辑器 -->
                        <div class="lg:col-span-2">
                            <div class="flex justify-between items-center mb-3">
                                <h3 class="text-lg font-semibold text-gray-700">代码查看器</h3>
                                <button id="runButton" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition hidden">
                                    <i class="fas fa-play"></i> 运行
                                </button>
                            </div>
                            <div id="codeContainer" class="bg-gray-900 rounded p-4">
                                <pre id="codeDisplay" class="code-editor text-gray-100 overflow-auto max-h-96">选择文件查看代码</pre>
                            </div>
                            
                            <!-- 运行结果 -->
                            <div id="runResult" class="mt-4 hidden">
                                <h4 class="text-md font-semibold text-gray-700 mb-2">运行结果</h4>
                                <div id="output" class="bg-black text-green-400 p-4 rounded font-mono text-sm overflow-auto max-h-48"></div>
                                <div id="error" class="bg-red-900 text-red-200 p-4 rounded font-mono text-sm mt-2 hidden"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentProject = null;
        let currentFile = null;

        // 上传功能
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const uploadStatus = document.getElementById('uploadStatus');

        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileUpload(files[0]);
            }
        });

        // 点击上传
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileUpload(e.target.files[0]);
            }
        });

        // 处理文件上传
        async function handleFileUpload(file) {
            const formData = new FormData();
            formData.append('codeFile', file);

            uploadStatus.classList.remove('hidden');
            uploadArea.style.display = 'none';

            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (result.success) {
                    currentProject = result.projectName;
                    displayProject(result.projectName, result.structure);
                } else {
                    alert('上传失败: ' + result.error);
                }
            } catch (error) {
                alert('上传错误: ' + error.message);
            } finally {
                uploadStatus.classList.add('hidden');
                uploadArea.style.display = 'block';
            }
        }

        // 显示项目结构
        function displayProject(projectName, structure) {
            document.getElementById('projectName').textContent = projectName;
            document.getElementById('projectArea').classList.remove('hidden');
            
            const fileTree = document.getElementById('fileTree');
            fileTree.innerHTML = '';
            renderFileTree(structure, fileTree, projectName);
        }

        // 渲染文件树
        function renderFileTree(structure, container, basePath = '') {
            Object.keys(structure).forEach(name => {
                const item = structure[name];
                const div = document.createElement('div');
                div.className = 'cursor-pointer hover:bg-gray-200 p-1 rounded';
                
                if (item.type === 'directory') {
                    div.innerHTML = `<i class="fas fa-folder text-yellow-500"></i> ${name}`;
                    div.onclick = () => {
                        const subContainer = document.createElement('div');
                        subContainer.className = 'ml-4';
                        subContainer.style.display = div.nextSibling?.style.display === 'none' ? 'block' : 'none';
                        
                        if (!div.nextSibling) {
                            renderFileTree(item.children, subContainer, basePath + '/' + name);
                            div.parentNode.insertBefore(subContainer, div.nextSibling);
                        } else {
                            div.nextSibling.style.display = div.nextSibling.style.display === 'none' ? 'block' : 'none';
                        }
                    };
                } else {
                    div.innerHTML = `<i class="fas fa-file text-blue-500"></i> ${name}`;
                    div.onclick = () => loadFile(basePath + '/' + item.path);
                }
                
                container.appendChild(div);
            });
        }

        // 加载文件内容
        async function loadFile(filePath) {
            try {
                const response = await fetch(`/file/${currentProject}/${filePath}`);
                const result = await response.json();
                
                if (result.type === 'file') {
                    currentFile = { path: filePath, language: result.language };
                    document.getElementById('codeDisplay').textContent = result.content;
                    document.getElementById('runButton').classList.remove('hidden');
                }
            } catch (error) {
                alert('加载文件失败: ' + error.message);
            }
        }

        // 运行代码
        document.getElementById('runButton').addEventListener('click', async () => {
            if (!currentFile) return;

            const runButton = document.getElementById('runButton');
            runButton.innerHTML = '<div class="loading"></div> 运行中...';
            runButton.disabled = true;

            try {
                const response = await fetch(`/run/${currentProject}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        filePath: currentFile.path,
                        language: currentFile.language
                    })
                });

                const result = await response.json();
                
                document.getElementById('runResult').classList.remove('hidden');
                document.getElementById('output').textContent = result.output || '(无输出)';
                
                if (result.error) {
                    document.getElementById('error').classList.remove('hidden');
                    document.getElementById('error').textContent = result.error;
                } else {
                    document.getElementById('error').classList.add('hidden');
                }

            } catch (error) {
                alert('运行失败: ' + error.message);
            } finally {
                runButton.innerHTML = '<i class="fas fa-play"></i> 运行';
                runButton.disabled = false;
            }
        });
    </script>
</body>
</html>
